package com.huang.auth.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huang.auth.constants.AuthConstants;
import com.huang.auth.converter.AuthUserVOConverter;
import com.huang.auth.converter.LoginLogsVOConverter;
import com.huang.auth.converter.LoginVOConverter;
import com.huang.auth.entity.po.AuthUserPO;
import com.huang.auth.entity.po.CommonLoginLogPO;
import com.huang.auth.entity.request.*;
import com.huang.auth.entity.to.CreatTokenTO;
import com.huang.auth.entity.to.LoginTO;
import com.huang.auth.entity.to.TokenInfoTO;
import com.huang.auth.entity.vo.*;
import com.huang.auth.service.AuthTokenService;
import com.huang.auth.service.AuthUserService;
import com.huang.entity.request.RPage;
import com.huang.entity.result.*;
import com.huang.utils.entity.to.TokenValResultTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author HuangShen
 * @Description 用户
 * @create 2021-09-25 7:58
 */
@RestController
@Api(tags = "用户模块")
@RequestMapping("/backend")
@Slf4j
public class AuthUserController {

    @Resource
    private AuthUserService authUserService;

    @Resource
    private AuthTokenService authTokenService;

    @Resource
    private LoginLogsVOConverter loginLogsVOConverter;
    @Resource
    private AuthUserVOConverter authUserVOConverter;

    private static final Logger logger = LoggerFactory.getLogger(AuthUserController.class);


    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public HStringResult<LoginVO> login(HttpServletRequest request, @RequestBody LoginRequest loginRequest) {
        String ip = request.getHeader("client-ip");
        String os = request.getHeader("operating-system");
        log.info("header:{},os:{}", ip, os);
        loginRequest.setIp(ip);
        loginRequest.setOs(os);
        // 查询用户信息
        LoginTO loginTO = authUserService.login(loginRequest);
        if (loginTO.getStatus() != AuthConstants.LOGIN_SUCCESS_CODE) {
            return ResultBuilder.failHSingle(loginTO.getMessage());
        }
        return ResultBuilder.successHSingle(LoginVOConverter.loginTO(loginTO));

    }

    @GetMapping("/logs/login/{pageNum}/{pageSize}")
    @ApiOperation(value = "登录日志")
    public HPageResult<LoginLogsVO> loginLogs(@RequestHeader("userId") String userId, @PathVariable Long pageNum, @PathVariable Long pageSize) {
        RPage rPage = new RPage();
        Page<CommonLoginLogPO> commonLoginLogPOPage = this.authUserService.loginLogs(userId, rPage);
        HPage page = new HPage();
        page.setPageNo(commonLoginLogPOPage.getCurrent());
        page.setPageSize(commonLoginLogPOPage.getSize());
        page.setAllCount(commonLoginLogPOPage.getTotal());
        page.setTotalPageNum(commonLoginLogPOPage.getPages());
        return ResultBuilder.successHPage(loginLogsVOConverter.batchConvert(commonLoginLogPOPage.getRecords()), page);

    }


    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToke")
    public HStringResult<LoginVO> refreshToken(@RequestParam String refreshToken) {
        TokenValResultTO tokenValResultTO = authTokenService.validationToken(refreshToken);
        if (tokenValResultTO.getCode() != 200) {
            log.info("刷新token 验证失败");
            return ResultBuilder.failHSingle(ResponseEnum.ERROR_LOGIN_ACL,tokenValResultTO.getMsg());
        }
        TokenInfoTO tokenInfoTO = JSON.parseObject(tokenValResultTO.getTokenInfo(), TokenInfoTO.class);
        CreatTokenTO creatTokenTO = authTokenService.creatToken(tokenInfoTO.getUserAccount());
        if (Objects.isNull(creatTokenTO)) {
            return ResultBuilder.successHSingleMsg("用户不存在");
        }
        LoginVO loginVO = new LoginVO();
        loginVO.setRefresh_token(creatTokenTO.getRefreshToken());
        loginVO.setAccess_token(creatTokenTO.getToken());
        loginVO.setExpires_in(creatTokenTO.getExpires_in());
        return ResultBuilder.successHSingle(loginVO);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "用户退出登录")
    public HStringResult<String> logout(@RequestHeader("access-token") String accessToken) {
        // 用户推出登录接口 空实现
        logger.info("用户推出登录,operatorId:{}", accessToken);
        return ResultBuilder.successHSingle();
    }

    @GetMapping("/userInfo")
    @ApiOperation(value = "用户信息")
    public HStringResult<AuthUserInfoVO> userInfo(@RequestHeader("userId") String operatorId) {
        AuthUserInfoVO authUserInfoVO = this.authUserService.queryUserInfoById(Long.valueOf(operatorId));
        if (Objects.isNull(authUserInfoVO)) {
            return ResultBuilder.failHSingle();
        }
        return ResultBuilder.successHSingle(authUserInfoVO);

    }
    @PostMapping("/authUsers")
    @ApiOperation(value = "用户列表")
    public HPageResult<AuthUserVO> userList(@RequestBody AuthUserQueryRequest authUserQueryRequest){
      Page<AuthUserPO> userPOPage=  this.authUserService.userListByPage(authUserQueryRequest);
        List<AuthUserVO> authUserVOS = authUserVOConverter.batchConvert(userPOPage.getRecords());
        HPage page = new HPage();
        page.setPageNo(userPOPage.getCurrent());
        page.setPageSize(userPOPage.getSize());
        page.setAllCount(userPOPage.getTotal());
        page.setTotalPageNum(userPOPage.getPages());
        return ResultBuilder.successHPage(authUserVOS, page);

    }

    @GetMapping("/userRoutes")
    @ApiOperation(value = "用户路由列表")
    public HStringResult<Set<RoutesVO>> userRoutes(@RequestHeader("userId") String operatorId) {

        Set<RoutesVO> routesVO = this.authUserService.queryMenuByUserId(operatorId);
        if (Objects.isNull(routesVO)) {
            return ResultBuilder.failHSingle(ResponseEnum.ERROR);
        }
        return ResultBuilder.successHSingle(routesVO);
    }

    @ApiOperation(value = "用户添加")
    @PostMapping("/authUser")
    public HStringResult<String> userAdd(@RequestHeader("userId") String userId, @RequestBody AuthUserAddRequest authUserAddRequest) {
        if (this.authUserService.userAdd(authUserAddRequest, Long.parseLong(userId))) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle("账号已注册");

    }

    @ApiOperation(value = "修改用户信息")
    @PutMapping("/authUser")
    public HStringResult<String> userEdit(@RequestHeader("userId") String operationId, @RequestBody AuthUserEditRequest authUserEditRequest) {
        authUserEditRequest.setUpdateUser(operationId);
        if (this.authUserService.userEdit(authUserEditRequest)) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle();
    }

    @ApiOperation(value = "修改启用状态")
    @PutMapping("/status/authUser")
    public HStringResult<String> changeStatus(@RequestHeader("userId") String operatorId, @RequestParam String account) {
        if (this.authUserService.changeUserStatus(account, Long.parseLong(operatorId))) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle("状态改变失败");
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/authUser")
    public HStringResult<String> delUser(@RequestHeader("userId") String operatorId, @RequestParam String account) {

        if (this.authUserService.delUser(account, Long.parseLong(operatorId))) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle("删除失败");
    }

    @ApiOperation(value = "重置密码")
    @PutMapping("/password")
    public HStringResult<String> resPassword(@RequestHeader("userId") String operatorId, @RequestParam String account) {

        if (this.authUserService.resPassword(account, Long.parseLong(operatorId))) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle("重置密码失败");
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/password")
    public HStringResult<String> resPassword(@RequestBody PasswordChangeRequest passwordChangeRequest) {

        if (this.authUserService.changePassword(passwordChangeRequest)) {
            return ResultBuilder.successHSingle();
        }
        return ResultBuilder.failHSingle("修改失败");
    }
    @ApiOperation(value = "用户拥有角色")
    @GetMapping("/authUser/roleIds")
    public HStringResult<List<String>> userRoleIds(@RequestParam String userId){
        List<String> roleIds = this.authUserService.queryRoleIdByUserId(userId);
        return ResultBuilder.successHSingle(roleIds);
    }




}
